package com.yjymm.edu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.yjymm.edu.config.AlipayConfig;
import com.yjymm.edu.exception.MyException;
import com.yjymm.edu.mapper.RechargeMapper;
import com.yjymm.edu.model.entity.Recharge;
import com.yjymm.edu.service.AlipayService;
import com.yjymm.edu.service.RechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * @author 95606
 */
@RestController
@RequestMapping("/alipay")
public class PayController {

    @Autowired
    private AlipayService alipayService;

    @Resource
    private RechargeService rechargeService;

    @Resource
    private RechargeMapper rechargeMapper;

    /**
     * 返回支付跳转链接
     * @param orderId
     * @return
     * @throws Exception
     */
    @GetMapping("/pay/{orderId}")
    public String payController(@PathVariable("orderId") String orderId) throws Exception {
        Recharge recharge = rechargeMapper.selectById(orderId);
        Double money = recharge.getMoney().doubleValue();
        String subject = "充值金额";
        return alipayService.webPagePay(recharge.getRechargeNum(), money, subject);
    }

    @PostMapping("/notify")
    public Boolean notifyPay(@RequestBody String returnData, HttpServletRequest request) throws Exception {
        if (!mySignVerified(request)) {
            throw new MyException("验签失败---");
        }
        if("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            String rechargeNum =  request.getParameter("out_trade_no");
            return rechargeService.pay(rechargeNum);
        }
        return Boolean.TRUE;
    }


    private boolean mySignVerified(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //String out_trade_no = request.getParameter("out_trade_no");
        // 商户订单号
        return AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
    }

}
